import {PlaneGeometry} from 'three';

export default class UITextGeometry extends PlaneGeometry{
    constructor(inline,font){
        const char = inline.glyph;
        const fontSize = inline.fontSize;
        super( fontSize, fontSize );
        console.log(inline,font);
        if ( char.match(/\s/g) === null ) {
            this.mapUVs( font, char );
            this.transformGeometry( font, fontSize, char, inline );
        } else {
            this.nullifyUVs();
            this.scale( 0, 0, 1 );
            this.translate( 0, fontSize / 2, 0 );
        }
    }

    transformGeometry( font, fontSize, char, inline ) {
        const charOBJ = font.chars.find( charOBJ => charOBJ.char === char );
        const common = font.common;
        const newHeight = charOBJ.height / common.lineHeight;
        const newWidth = (charOBJ.width * newHeight) / charOBJ.height;
        this.scale(
            newWidth,
            newHeight,
            1
        );
        this.translate(
            inline.width / 2,
            ( inline.height / 2 ) - inline.anchor,
            0
        );
    }
    mapUVs( font, char ) {
        const charOBJ = font.chars.find( charOBJ => charOBJ.char === char );
        const common = font.common;
        const xMin = charOBJ.x / common.scaleW;
        const xMax = (charOBJ.x + charOBJ.width ) / common.scaleW;
        const yMin =  1 -((charOBJ.y + charOBJ.height ) / common.scaleH);
        const yMax = 1 - (charOBJ.y / common.scaleH);
        const uvAttribute = this.attributes.uv;
        for ( let i = 0; i < uvAttribute.count; i ++ ) {
            let u = uvAttribute.getX( i );
            let v = uvAttribute.getY( i );
            [ u, v ] = (()=> {
                switch ( i ) {
                case 0 : return [ xMin, yMax ]
                case 1 : return [ xMax, yMax ]
                case 2 : return [ xMin, yMin ]
                case 3 : return [ xMax, yMin ]
                }
            })();
            uvAttribute.setXY( i, u, v );
        }
    }
    nullifyUVs() {
        const uvAttribute = this.attributes.uv;
        for ( let i = 0; i < uvAttribute.count; i ++ ) {
            uvAttribute.setXY( i, 0, 0 );
        }
    }

}